/*
 * vws_http_time.cpp
 *
 *  Created on: Sep 20, 2013
 *      Author: vscen
 */

#include "vws_http_time.h"

namespace vws {
bool vws_http_time::getDateStyle(int nIndex, char* pszBuffer, size_t nSize) {
	static char pszDateFmt[][48] = {
			{ "%3s, %02d %3s %04d %02d:%02d:%02d GMT" }, {
					"%s, %02d-%3s-%02d %02d:%02d:%02d GMT" }, {
					"%3s %3s %02d %02d:%02d:%02d %04d" } };
	static char* pszBuf = new char[PATH_MAX];
	if (pszBuf == NULL) {
		return false;
	} else {
		memset(pszBuf, 0, PATH_MAX);
	}
	time_t tt = time(NULL);
	struct tm* t = localtime(&tt);
	switch (nIndex) {
	case 0://RFC1123_DATE
		sprintf(pszBuf, pszDateFmt[0],
				vws_http_time::getWkdayString(t->tm_wday), t->tm_mday,
				vws_http_time::getMonthString(t->tm_mon), (t->tm_year + 1900),
				t->tm_hour, t->tm_min, t->tm_sec);
		break;
	case 1://RFC850_DATE
		sprintf(pszBuf, pszDateFmt[1], vws_http_time::getWeekdayString(
				t->tm_wday), t->tm_mday, vws_http_time::getMonthString(
				t->tm_mon), (t->tm_year + 1900), t->tm_hour, t->tm_min,
				t->tm_sec);
		break;
	case 2://ASCTIME_DATE
		sprintf(pszBuf, pszDateFmt[2],
				vws_http_time::getWkdayString(t->tm_wday),
				vws_http_time::getMonthString(t->tm_mon), t->tm_mday,
				t->tm_hour, t->tm_min, t->tm_sec, (t->tm_year + 1900));
		break;
	default:
		return false;
	}
	size_t nLength = strlen(pszBuf);
	if (nSize > nLength) {
		memset(pszBuffer, 0, nSize);
		strncpy(pszBuffer, pszBuf, nLength);
		delete[] pszBuf;
		return false;
	} else {
		return false;
	}
}

char* vws_http_time::getWkdayString(int nDay) {

	enum WKDAY_E {
		Sun = 0, Mon, Tue, Wed, Thu, Fri, Sat
	};
	static char pszWkday[8][4] = { { "Sun" }, { "Mon" }, { "Tue" }, { "Wed" },
			{ "Thu" }, { "Fri" }, { "Sat" }, { 0 } };
	if (nDay < Mon && nDay > Sat) {
		return NULL;
	}
	return pszWkday[nDay];
}

char* vws_http_time::getWeekdayString(int nWeekday) {
	enum WEEKDAY_E {
		Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
	};
	static char pszWeekday[8][10] = { { "Sunday" }, { "Monday" },
			{ "Tuesday" }, { "Wednesday" }, { "Thursday" }, { "Friday" }, {
					"Saturday" }, { 0 } };
	if (nWeekday < Monday && nWeekday > Saturday) {
		return NULL;
	}
	return pszWeekday[nWeekday];
}

char* vws_http_time::getMonthString(int nMonth) {
	enum MONTH_E {
		Jan = 0, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
	};
	static char pszMonth[][4] = { { "Jan" }, { "Feb" }, { "Mar" }, { "Apr" }, {
			"May" }, { "Jun" }, { "Jul" }, { "Aug" }, { "Sep" }, { "Oct" }, {
			"Nov" }, { "Dec" }, { 0 } };
	if (nMonth < Jan && nMonth > Dec) {
		return NULL;
	}
	return pszMonth[nMonth];
}
}
